package tcm.test.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tcm.test.mapper.OrderMapper;
import tcm.test.mapper.ProductMapper;
import tcm.test.pojo.dto.OrderDTO;
import tcm.test.pojo.entity.Order;
import tcm.test.pojo.entity.Product;
import tcm.test.service.OrderService;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    //创建新订单
    public void register(OrderDTO orderDTO) {
        Order order = new Order();

        BeanUtils.copyProperties(orderDTO, order);
        order.setCreateTime(LocalDateTime.now());

        Product product =productMapper.getById(order.getProductId());

        BigDecimal quantity = BigDecimal.valueOf(order.getQuantity());
        BigDecimal totalAmount = product.getPrice().multiply(quantity);
        
        order.setTotalAmount(totalAmount);
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.register(order);
    }

    //获取指定 ID 订单的详情
    public Order getById(Long id) {
        return orderMapper.getById(id);
    }

    //更新指定 ID 订单的详情
    public void update(OrderDTO orderDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setUpdateTime(LocalDateTime.now());

        Product product = productMapper.getById(order.getProductId());

        BigDecimal quantity = BigDecimal.valueOf(order.getQuantity());
        BigDecimal totalAmount = product.getPrice().multiply(quantity);
        order.setTotalAmount(totalAmount);

        orderMapper.update(order);
    }

    //删除指定id订单
    public void delete(Long id) {
        orderMapper.delete(id);
    }
}
